package com.intel.bluetooth;

import javax.bluetooth.RemoteDevice;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created by amanda.shan on 2016/9/1.
 */
public class ComBluDeviceThread extends Thread {

    private RemoteDevice remoteDevice;
    private BluetoothRFCommClientConnection connection;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;
    private byte[] recvBuf = new byte[1024];

    public boolean isRunning = true;

    private int mostWaitTime = 15 * 1000;

    private ServerConnect serverConnect;

    public ComBluDeviceThread(RemoteDevice remoteDevice,
                              BluetoothRFCommClientConnection connection) {

        this.remoteDevice = remoteDevice;
        this.connection = connection;

        serverConnect = new ServerConnect();
    }

    public void close() {
        try {
            isRunning = false;
            dataInputStream.close();
            dataOutputStream.close();
            serverConnect.stopClient();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public boolean initData() {
        try {
            this.dataInputStream = connection.openDataInputStream();
            this.dataOutputStream = connection.openDataOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Override
    public void run() {
        super.run();

        int temp = 0;

        if (serverConnect.connectServer()) {
            serverConnect.start();
            while (isRunning) {

                try {
                    if (dataInputStream.available() <= 0) {
                        Thread.sleep(5);
                        temp += 5;

                        if (temp >= mostWaitTime) {
                            serverConnect.stopClient();
                            break;
                        }
                    } else {
                        temp = 0;
                        int length = dataInputStream.read(recvBuf);

                        serverConnect.sendBytes(recvBuf, length);

                        try {
                            ProcessVstp.getInstance().parseVstpPacket(recvBuf,
                                    length);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void send(byte[] bytes, int len) {
        try {
            dataOutputStream.write(bytes, 0, len);
        } catch (IOException e) {
            e.printStackTrace();
            cancel();
        }
    }

    public void cancel() {
        isRunning = false;
    }

    public interface ComStateLis {
        public void comDisconnect();
    }

    class ServerConnect extends Thread {

        private OutputStream out;
        private InputStream in;
        private byte[] recvBuf = new byte[1024];
        private boolean mRun = false;
        private Socket ecgServerSocket;

        private boolean connectServer() {
            int reConnectTimes = 2;
            while (reConnectTimes > 0) {
                try {
                    ecgServerSocket = new Socket("localhost", 18788);
                    out = ecgServerSocket.getOutputStream();
                    in = ecgServerSocket.getInputStream();
                    return true;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                reConnectTimes--;
            }
            ecgServerSocket = null;
            return false;
        }

        public void run() {
            mRun = true;
            try {
                while (mRun) {
                    int len = in.read(recvBuf);

                    if (len > 0) {
                        send(recvBuf, len);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                close();
                serverConnect = new ServerConnect();
                initData();
                start();
            }
        }

        public void stopClient() {
            mRun = false;
            if (ecgServerSocket != null)
                try {
                    ecgServerSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            ecgServerSocket = null;

            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        public synchronized void sendBytes(byte[] buffer, int len)
                throws IOException {

            if (out != null) {
                out.write(buffer, 0, len);
                out.flush();
            } else {
                System.err.println("tcpClient out is null");
            }
        }
    }

    public RemoteDevice getRemoteDevice() {
        return remoteDevice;
    }

    public BluetoothRFCommClientConnection getConnection() {
        return connection;
    }

}
